import {Component, OnInit} from '@angular/core';
import {AlertComponent} from "../../unit/alert";
import {BasicService} from "../../unit/basic-service";
import {Photo, PhotoService} from "../../services/photo.service";

@Component({
    selector: 'app-identity-authentication',
    templateUrl: './identity-authentication.page.html',
    styleUrls: ['./identity-authentication.page.scss'],
})
export class IdentityAuthenticationPage implements OnInit {
    updateImg: boolean;
    currentType: number;
    saveLoading: boolean;
    photoList: Photo[] = [];
    userId: string;
    authImg = {front: false, back: false};

    constructor(public alertComponent: AlertComponent,
                public photoService: PhotoService,
                private basicService: BasicService,) {
    }

    ngOnInit() {
        this.userId = localStorage.getItem('cardNumber');

        this.photoService.addNewToGallery('init').then();
    }


    changeAuthentication() {
        if (!this.updateImg) {
            this.updateImg = true;
        } else {
            this.saveChange();
        }
    }

    saveChange() {
        this.basicService.postData('file/confirm', {idCard: this.userId}).then(res => {
            if (res === 0) {
                this.alertComponent.presentAlert('认证成功！').then();
                this.cancelUpdate();
            } else {
                this.alertComponent.presentAlert('认证失败！').then();
            }
        })
    }

    cancelUpdate() {
        this.updateImg = false;
    }

    addPhotoToGallery(type) {
        this.currentType = type;
        this.photoService.addNewToGallery('', this.updateImage.bind(this)).then();
    }

    updateImage(event) {
        this.photoList[this.currentType] = event;

        const currentFile = this.photoList[this.currentType];
        const formData = new FormData();
        formData.append('files', currentFile.filepath);
        formData.append('idCard', this.userId);
        formData.append('fileType', currentFile.fileType);
        formData.append('type', this.currentType.toString());

        this.saveLoading = true;
        this.basicService.postSingleFile('file/upload', formData).subscribe((res: any) => {
            if (res && res.code === 0) {
                this.checkAuth();
                this.alertComponent.presentAlert('上传成功！').then();
            }
            this.saveLoading = false;
        });
    }

    checkAuth() {
        if (this.currentType === 0) {
            this.authImg.front = true;
        } else {
            this.authImg.back = true;
        }
    }

}
